
import React from "react";
import { Select, Button, DatePicker, Input, Tooltip } from 'antd';
import {
  QuestionCircleFilled,
} from '@ant-design/icons';
import { apiGetEventStatisticsOverview, apiGetEventStatisticsTrend } from '@/request/dataBoard'
import './style/style.less'
import '@/font/iconfont.css'
import moment from 'moment';
import Card from "@/views/dataBoard/components/card.jsx"
import OnlineIncome from '@/views/dataBoard/components/IsOnlineIncomenew.jsx'
import _ from 'lodash'
import TheButton from "@/components/TheButton";
import Json2Excel from '@/utils/Json2Excel';

const { RangePicker } = DatePicker;
class Index extends React.Component {
  state = {
    dataSource: [],
    onlineName: "dataBoard",
    defaultValueTime: null,
    dateType: "day",
    selectVal: "onlineMall",
    selected: {},
    beginTime: moment().subtract(1, 'days').format('yyyy-MM-DD'),
    endTime: moment().subtract(1, 'days').format('yyyy-MM-DD'),
    time: '',
    chartData: {
      eventTrendList: [],
      dateList: []
    }
  }
  charts = React.createRef()
  async componentDidMount() {
    await this.getData();
    await this.getChartData();
    this.setState({
      time: moment().subtract(1, 'days').format('yyyy-MM-DD'),
    })
  }

  getData = async () => {
    let res = await apiGetEventStatisticsOverview({ "dateType": this.state.dateType, "businessType": this.state.selectVal, "beginDate": this.state.beginTime, "endDate": this.state.endTime })
    let UnitDispose = (data) => {
      if (!!data) {
        return data
        // if (data > 1000000) {
        //     return data > 1000000 ? (data / 1000000).toFixed(2) + "百万" : data
        // } else {
        //     return (data > 10000 ? (data / 10000).toFixed(2) + "万" : data || 0)
        // }
      } else {
        return 0
      }
    };
    if (res.code === 0) {
      let data = res.data ? res.data : []
      let dataSource = [];
      if (this.state.selectVal === "pet") {
        dataSource = [
          {
            top:
            {
              title: '访客人数',
              value: UnitDispose(data.storeVisitorCount),
              explain: "统计范围：统计周期内浏览任意页面 / 商城TAB及相关页面 / 宠圈TAB及相关页面 / 门店到店自提和洗护美容相关页面的去重人数。去重逻辑：账户在统计时间范围内访问多次只记为一个。注：不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.storeVisitorCountTrend,

            },
          },
          {
            top:
            {
              title: '查看帖子详情人数',
              value: UnitDispose(data.dynamicViewCount),
              explain: "统计范围：统计周期内用户点击进入帖子详情页浏览的人数去重逻辑：账户在统计时间范围内访问多次只记为一个。注：不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.dynamicViewCountTrend
            }

          },
          {
            top:
            {
              title: '人均查看帖子数',
              value: UnitDispose(data.dynamicSingleViewCount),
              explain: "帖子数/访客人数",
              yesterday: data.dynamicSingleViewCountTrend
            }
          },
          {
            top:
            {
              title: '发帖人数',
              value: UnitDispose(data.dynamicCreateCount),
              explain: "统计范围：统计周期内用户发布帖子（不考虑审核是否通过）的人数去重逻辑：根据账号去重，不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.dynamicCreateCountTrend
            }
          },
          {
            top:
            {
              title: '点赞人数',
              value: UnitDispose(data.dynamicLikeCount),
              explain: "统计范围：统计周期内用户对帖子点赞的人数；去重逻辑：根据账号去重，不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.dynamicLikeCountTrend
            }
          },
          {
            top:
            {
              title: '分享人数',
              value: UnitDispose(data.dynamicShareCount),
              explain: "统计范围：统计周期内用户对帖子分享的人数去重逻辑：根据账号去重，不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.dynamicShareCountTrend
            }
          },
          {
            top:
            {
              title: '评论人数',
              value: UnitDispose(data.dynamicCommentCount),
              explain: "统计范围：统计周期内用户对帖评论的人数去重逻辑：根据账号去重，不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.dynamicCommentCountTrend
            }
          },
          {
            top:
            {
              title: '平均停留时长(分钟)',
              value: UnitDispose(data.stayDuration ? (data.stayDuration / 60).toFixed(1) : 0),
              explain: "停留总时长/访客人数 停留总时长：统计周期内打开相关页面到退出的浏览时长之和",
              yesterday: data.stayDurationTrend
            }
          },
        ]
      } else if (this.state.selectVal.includes('mhc')) {
        dataSource = [
          {
            top:
            {
              title: '服务选择页访客数',
              value: UnitDispose(data.visitorCount),
              explain: "当日浏览上门服务选择页的人数（根据用户id去重）",
              yesterday: data.visitorCountTrend,
            },
          },
          {
            top:
            {
              title: '提单页访客数',
              value: UnitDispose(data.orderVisitorCount),
              explain: "当日浏览提单页的访客人数（根据用户id去重）",
              yesterday: data.orderVisitorCountTrend
            }
          },
          {
            top:
            {
              title: '预约-提单页转化率',
              value: data.orderVisitorRatio ? UnitDispose(((Number(data.orderVisitorRatio) * 100).toFixed(2))) + '%' : 0,
              explain: "预约-提单页转化率= 提单页访客数 / 服务选择页访客数 *100%",
              yesterday: data.orderVisitorRatioTrend
            }
          },
          {
            top:
            {
              title: '支付人数',
              value: UnitDispose(data.storePayCount),
              explain: "当日上门服务订单的支付人数之和（根据用户id去重）",
              yesterday: data.storePayCountTrend
            }
          },
          {
            top:
            {
              title: '访客支付转化率',
              value: UnitDispose(data.storePayRatio),
              value: data.storePayRatio ? UnitDispose(((Number(data.storePayRatio) * 100).toFixed(2))) + '%' : 0,
              explain: "访客支付转化率=支付人数 / 服务选择页访客数 * 100%",
              yesterday: data.storePayRatioTrend
            }
          },
          {
            top:
            {
              title: '支付订单数',
              value: UnitDispose(data.storeOrderCount),
              explain: "下单时间在筛选时间段内，且已支付的订单的数量之和（注：单个用户一次性下单多次喂养 或 多只洗护，则统计为多笔订单；变更产生的支付订单行需要统计在内）",
              yesterday: data.storeOrderCountTrend
            }
          },
          {
            top:
            {
              title: '支付金额',
              value: UnitDispose(data.storePayPrice ? (data.storePayPrice / 60).toFixed(2) : 0),
              explain: "当日支付订单的实付金额之和",
              yesterday: data.storePayPriceTrend
            }
          },
          {
            top:
            {
              title: '客单价',
              value: data.storePaySinglePrice ? UnitDispose(((Number(data.storePaySinglePrice) / 100)).toFixed(2)) : 0,
              explain: "客单价=支付金额 / 支付人数",
              yesterday: data.storePaySinglePriceTrend
            }
          },
          {
            top:
            {
              title: '退款订单数',
              value: UnitDispose(data.refundCount),
              explain: "退款成功时间在筛选时间段内的订单数量之和（注：单个用户一次性退款成功多次喂养 或 多只洗护，则统计为多笔订单；变更未产生支付的变更退款订单行不计）",
              yesterday: data.refundCountTrend
            }
          },
          {
            top:
            {
              title: '退款金额',
              value: UnitDispose(data.refundPrice ? (data.refundPrice / 60).toFixed(2) : 0),
              explain: "筛选时间段内，退款成功的订单的实退金额之和，包括由于变更而导致的退款金额",
              yesterday: data.refundPriceTrend
            }
          },
        ]
      } else {
        dataSource = [
          {
            top:
            {
              title: '访客人数',
              value: UnitDispose(data.storeVisitorCount),
              explain: "统计范围：统计周期内浏览任意页面 / 商城TAB及相关页面 / 宠圈TAB及相关页面 / 门店到店自提和洗护美容相关页面的去重人数。去重逻辑：账户在统计时间范围内访问多次只记为一个。注：不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.storeVisitorCountTrend
            },
          },
          {
            top:
            {
              title: '加购人数',
              value: UnitDispose(data.storeCartCount),
              explain: "统计范围：统计周期内在对应页面 （商城TAB及相关页面 / 宠圈TAB及相关页面 / 门店到店自提和洗护美容）有加购商品动作的去重人数。去重逻辑：账户在统计时间范围内访问多次只记为一个。注：不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.storeCartCountTrend
            }
          },
          {
            top:
            {
              title: '访客加购率',
              value: data.storeCartRatio ? UnitDispose(((Number(data.storeCartRatio) * 100).toFixed(2))) + "%" : 0,
              explain: "加购人数/访客人数",
              yesterday: data.storeCartRatioTrend
            }


          },
          {
            top:
            {
              title: '支付人数',
              value: UnitDispose(data.storePayCount),
              explain: "未剔除事后退款的人数（退款包括售中和售后的仅退款和退货退款）去重逻辑：账户在统计时间范围内支付多笔订单多次只记为一个。注：不会根据设备id相同去重，即会员账号登录多个设备只统计一次",
              yesterday: data.storePayCountTrend
            }
          },
          {
            top:
            {
              title: '访客支付转化率',
              value: data.storePayRatio ? UnitDispose(((Number(data.storePayRatio) * 100).toFixed(2))) + '%' : 0,
              explain: "支付人数/访客人数",
              yesterday: data.storePayRatioTrend
            }
          },
          {
            top:
            {
              title: '支付订单数',
              value: UnitDispose(data.storeOrderCount),
              explain: "未剔除事后退款订单（退款包括售中和售后的仅退款和退货退款）",
              yesterday: data.storeOrderCountTrend
            }
          },
          {
            top:
            {
              title: '支付金额',
              value: data.storePayPrice ? UnitDispose((data.storePayPrice / 100).toFixed(2)) : 0,
              explain: "未剔除事后退款金额（退款包括售中和售后的仅退款和退货退款）",
              yesterday: data.storePayPriceTrend
            }
          },
          {
            top:
            {
              title: '客单价',
              value: data.storePaySinglePrice ? UnitDispose((data.storePaySinglePrice / 100).toFixed(2)) : 0,
              explain: "支付金额数/支付人数",
              yesterday: data.storePaySinglePriceTrend
            }
          },
          {
            top:
            {
              title: '平均停留时长(分钟)',
              value: UnitDispose(data.stayDuration ? (data.stayDuration / 60).toFixed(1) : 0),
              explain: "停留总时长/访客人数  停留总时长：统计周期内打开相关页面到退出的浏览时长之和",
              yesterday: data.stayDurationTrend
            }
          },
          {
            top:
            {
              title: '退款订单数',
              value: UnitDispose(data.refundCount),
              explain: "在时间范围内申请退款并退款成功的订单数",
              nowData: true,
              yesterday: data.refundCountTrend
            }
          },
          {
            top:
            {
              title: '退款金额',
              value: data.refundPrice ? UnitDispose(((Number(data.refundPrice) / 100)).toFixed(2)) : 0,
              explain: "在时间范围内申请退款并退款成功订单的退款金额之和",
              nowData: true,
              yesterday: data.refundPriceTrend
            }
          },
          // {
          //   top:
          //   {
          //     title: ' 新注册用户数',
          //     value: UnitDispose(data.newMemberCount),
          //     explain: "",
          //     // nowData: true,
          //     yesterday: data.newMemberCountTrend
          //   }
          // },
          // {
          //   top:
          //   {
          //     title: '新用户支付金额',
          //     value: data.newMemberPayPrice ? UnitDispose(((Number(data.newMemberPayPrice) / 100)).toFixed(2)) : 0,
          //     explain: "",
          //     // nowData: true,
          //     yesterday: data.newMemberPayPriceTrend
          //   }
          // },
          // {
          //   top:
          //   {
          //     title: '新用户支付订单数',
          //     value: UnitDispose(data.newMemberPayOrderCount),
          //     explain: "",
          //     // nowData: true,
          //     yesterday: data.newMemberPayOrderCountTrend
          //   }
          // },
          // {
          //   top:
          //   {
          //     title: '新用户支付用户数',
          //     value: UnitDispose(data.newMemberPayMemberCount),
          //     explain: "",
          //     // nowData: true,
          //     yesterday: data.newMemberPayMemberCountTrend
          //   }
          // },
          // {
          //   top:
          //   {
          //     title: '新用户支付金额占比',
          //     value: UnitDispose(data.newMemberPayPriceRatio) + "%",
          //     explain: "",
          //     // nowData: true,
          //     yesterday: data.newMemberPayPriceRatioTrend
          //   }
          // },
          // {
          //   top:
          //   {
          //     title: '老用户支付金额占比',
          //     value: UnitDispose(data.oldMemberPayPriceRatio) + "%",
          //     explain: "",
          //     // nowData: true,
          //     yesterday: data.oldMemberPayPriceRatioTrend
          //   }
          // },
        ]
      }
      this.setState({ dataSource })
    }
  }
  getChartData = async () => {
    let res = await apiGetEventStatisticsTrend({ "dateType": this.state.dateType, "businessType": this.state.selectVal, "beginDate": this.state.beginTime, "endDate": this.state.endTime })
    if (res.data && res.code === 0) {
      let data = res.data;
      this.setState({
        chartData: {}
      }, () => {
        this.setState({
          chartData: data
        })
      })
    }
  }

  handleChange = async (value) => {
    this.setState({
      onlineName: value.includes('mhc') ? 'dataBoardMhc' : 'dataBoard',
      selectVal: value
    }, () => {
      this.getData();
      this.getChartData()
    })
  };


  onChange = (dates, dateStrings, type) => {

    if (dates) {

      let beginTime = "";
      let endTime = ""
      let time = ""
      if (type == "year") {
        beginTime = moment(dates).startOf('year').format('YYYY-MM-DD')
        endTime = moment(dates).endOf('year').format('YYYY-MM-DD')
        time = beginTime + '~' + endTime
      }
      if (type == "month") {
        beginTime = moment(dates).startOf('month').format('YYYY-MM-DD')
        endTime = moment(dates).endOf('month').format('YYYY-MM-DD')
        time = beginTime + '~' + endTime
      }
      if (type == "week") {
        beginTime = moment(dates).startOf('week').format('YYYY-MM-DD')
        endTime = moment(dates).endOf('week').format('YYYY-MM-DD')
        time = beginTime + '~' + endTime
      }
      if (type == "day") {
        beginTime = dateStrings
        endTime = dateStrings
        time = beginTime
      }
      if (type == "maybe") {
        beginTime = dateStrings[0]
        endTime = dateStrings[1]
        time = beginTime + "~" + endTime
      }

      this.setState({
        beginTime: beginTime,
        endTime: endTime,
        dateType: type == "maybe" ? "day" : type,
        time: time
      }, () => {
        this.getData();
        this.getChartData()
      })
    } else {
    }
  };
  open = (a) => {
    this.setState({
      defaultValueTime: null
    })
  }
  setQuery = (params) => {
    this.setState({
      selected: params
    })
  }
  componentWillUnmount() {

  }

  toExprot = () => {
    const { dataSource, selectVal, beginTime, endTime } = this.state
    this.setState({
      exportLoading: true
    })
    let label = ""
    switch (selectVal) {
      case "mhcAll":
        label = "上门服务-全部"
        break;
      case "mhcFeed":
        label = "上门服务-喂养"
        break;
      case "mhcCare":
        label = "上门服务-洗护"
        break;
      case "onlineMall":
        label = "线上商城"
        break;
      case "pet":
        label = "宠圈"
        break;
      case "store":
        label = "门店"
        break;
      default:
        break;
    }
    dataSource.map((item, index) => {
      if (item.top.yesterday > 0) {
        item.trend = "上升"
      } else if (item.top.yesterday < 0) {
        item.trend = "下降"
      } else {
        item.trend = "-"
      }
      item.title = item.top.title
      item.value = item.top.value
      item.yesterday = (item.top.yesterday * 100).toFixed(2) + "%"
    })
    const option = {
      header: [
        {
          title: '业务范围：' + label + "\r\n" + "统计时间：" + beginTime + "-" + endTime,
          prop: '',
          children: [
            { prop: 'title', title: '数据名称' },
            { prop: 'value', title: '数据值', valueType: 'n' },
            { prop: 'trend', title: '环比趋势' },
            { prop: 'yesterday', title: '环比幅度', valueType: 'n' }
          ]
        }
      ],
      fileName: "概览数据",
      dataSource,
    }
    this.setState({
      exportLoading: false
    })
    Json2Excel(option);
  }

  render() {
    const { onlineName, dataSource, time, chartData, defaultValueTime, exportLoading } = this.state
    const timeRange = time.split('~')

    return <div className={"p-layout-box configuration"}>
      <p className="realTitle">概览数据 <span>统计时间：{time}</span></p>
      <div className="realTime">
        <div>
          业务范围：
          <Select
            defaultValue="onlineMall"
            style={{
              width: 200,
            }}
            onChange={this.handleChange}
            options={[
              {
                value: 'mhcAll',
                label: '上门服务-全部',
              },
              {
                value: 'mhcFeed',
                label: '上门服务-喂养',
              },
              {
                value: 'mhcCare',
                label: '上门服务-洗护',
              },
              {
                value: 'onlineMall',
                label: '线上商城',
              },
              {
                value: 'pet',
                label: '宠圈',
              },
              {
                value: 'store',
                label: '门店',
              },
            ]}
          />

        </div>
        <div className="searchBtn">
          <div className="box" id="area">
            <Button type="primary">年</Button>
            <DatePicker getPopupContainer={() => document.getElementById('area')} allowClear={false} onOpenChange={this.open} picker="year" value={defaultValueTime} onChange={(a, b) => this.onChange(a, b, "year")} className="dateBtn"  ></DatePicker>
          </div>
          <div className="box" id="area">
            <Button type="primary">月</Button>
            <DatePicker getPopupContainer={() => document.getElementById('area')} allowClear={false} onOpenChange={this.open} format={'YYYY-MM'} value={defaultValueTime} picker="month" onChange={(a, b) => this.onChange(a, b, "month")} className="dateBtn"  ></DatePicker>
          </div>
          <div className="box" id="area">
            <Button type="primary" >周</Button>
            <DatePicker getPopupContainer={() => document.getElementById('area')} allowClear={false} onOpenChange={this.open} value={defaultValueTime} picker="week" onChange={(a, b) => this.onChange(a, b, "week")} className="dateBtn"  ></DatePicker>
          </div>
          <div className="box" id="area">
            <Button type="primary" >日</Button>
            <DatePicker getPopupContainer={() => document.getElementById('area')} allowClear={false} onOpenChange={this.open} format={'YYYY-MM-DD'} value={defaultValueTime} onChange={(a, b) => this.onChange(a, b, "day")} className="dateBtn"  ></DatePicker>
          </div>
          <div className="box" id="area">
            <Tooltip title="自定义支持在可选时间范围内，对任意连续自然天的数据进行分析，人群相关的指标默认将单日的数据直接相加计算。 自定义周期查询下，默认将所选时间段与上一个时间段进行对比，例如，若查询时间选择11.04-11.06（本期数），则上一个时间段为11.01-11.03（上期数），对比值=（本期数－上期数）÷ 上期数 ×100%。"> <Button type="primary">自定义<QuestionCircleFilled /></Button></Tooltip>
            <RangePicker getPopupContainer={() => document.getElementById('area')} allowClear={false} onOpenChange={this.open} format={'YYYY-MM-DD'} value={defaultValueTime} onChange={(a, b) => this.onChange(a, b, "maybe")} className="dateBtn"  ></RangePicker>
          </div>
        </div>
        <div style={{ marginLeft: '40px' }}>
          <TheButton haspermi={["dataBoard:index:export"]} loading={exportLoading} type="primary" size="middle" onClick={this.toExprot}>导出</TheButton>
        </div>
      </div>
      <div className="card-box">
        {
          dataSource.map((v, i) => {
            return <Card key={i} top={v.top} nowData={v.top.nowData} />
          })
        }
      </div>
      <div style={{ marginTop: 30, fontWeight: 700, fontSize: 22 }}>指标趋势</div>
      <OnlineIncome data={chartData} name={onlineName} setQuery={this.setQuery} style={{ overflow: 'auto' }} height={'500px'} width={'100%'} />
    </div>
  }
}

export default Index;